import time
from config.settings import get_config
from base.base_page import BasePage

"""
封装功能函数

"""
class New_Access_Time_Frequency(BasePage):
    def __init__(self, driver, device_type, logger=None):
        super().__init__(driver, device_type, logger=logger)  # 传递日志实例
        self.driver = driver
        self.config = get_config(device_type)  # 获取全局配置

    def create_access_time_frequency(self, interface_name, access_time_limit, access_time_begin, access_time_end,
                                     request_limit, request_frequency):
        # 进入时间、次数配置
        self.enter_new_access_time_frequency()
        # 停止已有配置状态
        self.update_access_time_frequency_status(interface_name, access_time_frequency_status='停止')
        # 删除已有名称的配置
        self.delete_access_time_frequency(interface_name)
        # 新建时间、次数配置
        self.newly_access_time_frequency()
        # 选择数据接口名称
        self.input_data_interface(interface_name)
        # 访问时间段
        self.input_access_time_limit(access_time_limit)
        self.input_access_time(access_time_limit, access_time_begin, access_time_end)
        # 输入时间限制
        self.input_request_frequency_limit(request_limit)
        # 输入次数
        self.input_request_frequency(request_limit, request_frequency)
        # 保存配置
        self.save_access_time_frequency(interface_name)

    def enter_new_access_time_frequency(self):
        # 进入新建访问数据接口时间、次数配置
        status = self.find_element('first_level_menu_module', 'interface_security_configure_status')
        if "ivu-menu-opened" in status.get_attribute("class"):
            pass
        else:
            self.click('first_level_menu_module', 'interface_security_configure')
        status = self.find_element('second_level_menu_module', 'ext_service_access_security_status')
        if "ivu-menu-opened" in status.get_attribute("class"):
            if self.quick_check_element('new_access_time_frequency', 'data_interface_name'):
                pass
            else:
                self.click('second_level_menu_module', 'ext_service_access_security')
        else:
            self.click('second_level_menu_module', 'ext_service_access_security')
            self.click('third_fourth_level_menu_module', 'new_access_time_frequency')
            self.soft_assert_element_visible('new_access_time_frequency', 'data_interface_name')

    def newly_access_time_frequency(self):
        # 点击新建按钮
        self.click('common_elements', 'newly_built')
        self.soft_assert_element_visible('new_access_time_frequency', 'input_data_interface')

    def delete_access_time_frequency(self, interface_name):
        """
        支持分页查找并删除对象
        :param interface_name: 要删除的对象名称
        """
        if self.quick_check_element('common_elements', 'no_data'):
            pass
        else:
            current_page = 1
            while True:
                # 获取当前页所有对象名称
                name_elements = self.find_elements('new_access_time_frequency', 'access_time_frequency_name')
                # 遍历当前页
                for row_index, element in enumerate(name_elements, 1):
                    if element.text.strip() == interface_name:
                        self._delete_current_row(row_index)
                        if self.quick_check_element('common_elements', 'delete_success'):
                            self.logger.info(f"成功删除第{current_page}页的'{interface_name}'")
                        else:
                            self.logger.info(f"未成功删除第{current_page}页的'{interface_name}'")
                        return
                # 尝试翻页
                if not self._go_to_next_page():
                    break
                current_page += 1 # 等待分页加载

    def _delete_current_row(self, row_index):
        """执行单行删除操作"""
        delete_btn = self.find_dynamic_element(
            'new_access_time_frequency',
            'delete_access_time_frequency_all',
            row_index
        )
        # 点击删除按钮
        delete_btn.click()
        self.click('common_elements', 'confirm_button')
        self.find_element('common_elements', 'delete_success')

    def update_access_time_frequency_status(self, interface_name, access_time_frequency_status):
        """ 修改状态 """
        self.enter_new_access_time_frequency()
        if self.quick_check_element('common_elements', 'no_data'):
            pass
        else:
            result =  self.query_paged_data(
                search_locator='access_time_frequency_name',
                target_locator='access_time_frequency_status_all',
                value=interface_name,
                param_name='interface_name'
            )
            if result is None:
                pass
            else:
                if "ivu-switch-checked" in result.get_attribute("class"):
                    if access_time_frequency_status == '启动':
                        pass
                    else:
                        result.click()
                        self.find_element('common_elements', 'status_update_success')
                        self.logger.info(f"时间、次数配置 '{interface_name}'停止成功")
                else:
                    if access_time_frequency_status == '停止':
                        pass
                    else:
                        result.click()
                        self.find_element('common_elements', 'status_update_success')
                        self.logger.info(f"时间、次数配置 '{interface_name}'启动成功")

    def input_data_interface(self, interface_name):
        """ 输入数据接口 """
        selected_result = self.select_interface_options(
            element_locator='input_data_interface',
            values=interface_name,
            param_name='interface_name'
        )
        return selected_result

    def input_access_time_limit(self, access_time_limit):
        """ 输入访问时间段限制 """
        if access_time_limit == '无限制' or access_time_limit == '':
            pass
        else:
            selected_result = self.select_interface_options(
                element_locator='access_time_limit',
                values=access_time_limit,
                param_name='access_time_limit'
            )
            return selected_result

    def input_access_time(self, access_time_limit, access_time_begin, access_time_end):
        """ 输入限制时间 """
        if access_time_limit == '时间限制':
            self.click('new_access_time_frequency', 'access_time_begin')
            self.select_interface_options(
                element_locator='input_access_time_begin',
                values=access_time_begin,
                param_name='access_time_begin'
            )
            self.click('new_access_time_frequency', 'access_time_end')
            end_time = self.select_interface_options(
                element_locator='input_access_time_end',
                values=access_time_end,
                param_name='access_time_end'
            )
            return end_time
        else:
            pass

    def input_request_frequency_limit(self, request_limit):
        """ 输入请求次数限制 """
        selected_result = self.select_interface_options(
            element_locator='request_frequency_limit',
            values=request_limit,
            param_name='request_limit'
        )
        return selected_result

    def select_access_time_frequency_name(self, interface_name):
        """ 查看界面是否存在保存的接口名称 """
        selected_result = self.select_interface_options(
            element_locator='access_time_frequency_name',
            values=interface_name,
            param_name='interface_name'
        )
        return selected_result

    def save_access_time_frequency(self, interface_name):
        self.click('new_access_time_frequency', 'save_access_time_frequency')
        if self.find_element('common_elements', 'add_success'):
            self.select_access_time_frequency_name(interface_name)
            self.logger.info(f'接口时间、次数配置：{interface_name} 保存成功')

    def input_request_frequency(self, request_limit, request_frequency):
        if request_limit == '无限制' or '':
            pass
        else:
            self.input_text('new_access_time_frequency', 'input_request_frequency', request_frequency)
            self.soft_assert_input_value('new_access_time_frequency', 'input_request_frequency', request_frequency)

    def get_visit_time(self, interface_name):
        """ 获取访问时间段 """
        self.enter_new_access_time_frequency()
        result =  self.query_paged_data(
            search_locator='access_time_frequency_name',
            target_locator='access_time_frequency_time_all',
            value=interface_name,
            param_name='interface_name'
        ).text.strip()
        self.logger.info(f"找到接口 '{interface_name}' 的访问时间段：{result}")
        return result

    def query_paged_data(self, search_locator: str, target_locator: str, value: str, param_name: str):
        """通用分页数据查询方法（返回符合的元素、单值）"""
        # 标准化输入值
        target_text = str(value).strip()
        current_page = 1

        while True:
            # 获取当前页所有可选项
            options = self.find_elements('new_access_time_frequency', search_locator)

            # 遍历匹配选项
            for row_index, element in enumerate(options, 1):
                option_text = element.text.strip()
                if option_text == target_text:
                    # 获取同行的目标元素
                    target_element = self.find_dynamic_element(
                        'new_access_time_frequency',
                        target_locator,
                        row_index
                    )
                    return target_element  # 直接返回元素
                    # return target_element.text.strip() #直接返回字符串

            # 尝试翻页
            if not self._go_to_next_page():
                self.logger.debug(f"未找到匹配项: {target_text}，已遍历 {current_page} 页")
                return None  # 静默返回None

            current_page += 1

    def select_interface_options(self, element_locator: str, values: list, param_name: str):
        """通用接口选项选择方法（基础方法）"""
        # 类型统一处理
        if not isinstance(values, list):
            values = [values]

        selected = []
        for value in values:
            # 获取所有可选项
            options = self.find_elements('new_access_time_frequency', element_locator)

            # 标准化输入值
            target_text = str(value).strip()

            # 遍历匹配选项
            found = False
            for option in options:
                option_text = option.text.strip()
                if option_text == target_text:
                    self.highlight_element(option)  # 可视化点击元素
                    option.click()
                    selected.append(option_text)
                    found = True
                    break

            if not found:
                available_options = [opt.text.strip() for opt in options]
                raise ValueError(
                    f"参数 {param_name} 未找到选项: '{target_text}'\n"
                    f"可用选项: {available_options}"
                )
            return selected